<template>
  <!-- 规格弹窗 -->
  <su-popup :show="authType !== ''" round="10" :showClose="true" @close="closeAuthModal">
    <view v-if="true" class="login-box">
      <view>
        <image class="avatar-img"
          :src="sheep.$url.cdn('https://txz-1332973494.cos.ap-guangzhou.myqcloud.com/static/img/shop/txz.jpg')"
          mode="aspectFill">
        </image>
        <view class="tit ss-m-t-20 ss-m-b-80">童行者管理端</view>
        <!-- 表单项 -->
        <uni-forms ref="accountLoginRef" v-model="state.model" :rules="state.rules" validateTrigger="bind"
          labelAlign="center">
          <uni-forms-item border>
            <uni-easyinput placeholder="请输入账号" prefixIcon="person" v-model="state.model.username">
            </uni-easyinput>
          </uni-forms-item>
          <uni-forms-item name="password" border>
            <uni-easyinput type="password" placeholder="请输入密码" prefixIcon="locked" v-model="state.model.password">
            </uni-easyinput>
          </uni-forms-item>
          <uni-forms-item name="code" class="vf-code" border>
            <uni-easyinput type="text" placeholder="请输入验证码" prefixIcon="locked" class="custom-input"
              v-model="state.model.captchaVerification">
            </uni-easyinput>
            <jp-verification-literalness ref="verifiCode" :contentHeight="36"></jp-verification-literalness>
          </uni-forms-item>

        </uni-forms>
        <!-- <button class="ss-reset-button forgot-btn" @tap="showAuthModal('resetPassword')">
          忘记密码
        </button> -->
        <button class="ss-reset-button login-btn-start" @tap="accountLoginSubmit">登录</button>
        <view class="agreement-box ss-flex ss-row-center" :class="{ shake: currentProtocol }">
          <label class="radio ss-flex ss-col-center" @tap="onChange">
            <radio :checked="state.protocol" color="#ff3000" style="transform: scale(0.8)" @tap.stop="onChange" />
            <view class="agreement-text ss-flex ss-col-center ss-m-l-8">
              我已阅读并遵守
              <view class="tcp-text" @tap.stop="onProtocol('用户协议')"> 《用户协议》 </view>
              <view class="agreement-text">与</view>
              <view class="tcp-text" @tap.stop="onProtocol('隐私协议')"> 《隐私协议》 </view>
            </view>
          </label>
        </view>

      </view>
      <view class="safe-box" />
    </view>
    <view v-else class="login-wrap">
      <!-- 1. 账号密码登录 accountLogin -->
      <account-login v-if="authType === 'accountLogin'" :agreeStatus="state.protocol" @onConfirm="onConfirm" />

      <!-- 2. 短信登录  smsLogin -->
      <sms-login v-if="authType === 'smsLogin'" :agreeStatus="state.protocol" @onConfirm="onConfirm" />

      <!-- 3. 忘记密码 resetPassword-->
      <reset-password v-if="authType === 'resetPassword'" />

      <!-- 4. 绑定手机号 changeMobile -->
      <change-mobile v-if="authType === 'changeMobile'" />

      <!-- 5. 修改密码 changePassword-->
      <changePassword v-if="authType === 'changePassword'" />

      <!-- 6. 微信小程序授权 -->
      <mp-authorization v-if="authType === 'mpAuthorization'" />

      <!-- 7. 第三方登录 -->
      <view v-if="['accountLogin', 'smsLogin'].includes(authType)"
        class="auto-login-box ss-flex ss-flex-col ss-row-center ss-col-center">
        <!-- 7.1 微信小程序的快捷登录 -->
        <view v-if="sheep.$platform.name === 'WechatMiniProgram' && !isProcessing" class="ss-flex register-box"
          @click.prevent="get">
          <button class="ss-reset-button login-btn-start"> 手机号快捷登录 </button>
        </view>
        <view v-else-if="sheep.$platform.name === 'WechatMiniProgram' && isProcessing" class="ss-flex register-box">
          <button class="ss-reset-button login-btn-start" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
            手机号快捷登录
          </button>
        </view>

        <!-- 7.2 微信的公众号、App、小程序的登录，基于 openid + code -->
        <!-- #ifndef MP-WEIXIN -->
        <button v-if="
            ['WechatOfficialAccount', 'WechatMiniProgram', 'App'].includes(sheep.$platform.name) &&
            sheep.$platform.isWechatInstalled
          " @tap="thirdLogin('wechat')" class="ss-reset-button auto-login-btn">
          <image class="auto-login-img" :src="sheep.$url.static('/static/img/shop/platform/wechat.png')" />
        </button>
        <!-- #endif -->

        <!-- 7.3 iOS 登录 TODO 芋艿：等后面搞 App 再弄 -->
        <button v-if="sheep.$platform.os === 'ios' && sheep.$platform.name === 'App'" @tap="thirdLogin('apple')"
          class="ss-reset-button auto-login-btn">
          <image class="auto-login-img" :src="sheep.$url.static('/static/img/shop/platform/apple.png')" />
        </button>
      </view>

      <!-- 用户协议的勾选 -->
      <view v-if="['accountLogin', 'smsLogin'].includes(authType)" class="agreement-box ss-flex ss-row-center"
        :class="{ shake: currentProtocol }">
        <label class="radio ss-flex ss-col-center" @tap="onChange">
          <radio :checked="state.protocol" color="var(--ui-BG-Main)" style="transform: scale(0.8)"
            @tap.stop="onChange" />
          <view class="agreement-text ss-flex ss-col-center ss-m-l-8">
            我已阅读并遵守
            <view class="tcp-text" @tap.stop="onProtocol('用户协议')"> 《用户协议》 </view>
            <view class="agreement-text">与</view>
            <view class="tcp-text" @tap.stop="onProtocol('隐私协议')"> 《隐私协议》 </view>
          </view>
        </label>
      </view>
      <view class="safe-box" />
    </view>
  </su-popup>
</template>

<script setup>
  import {
    computed,
    reactive,
    ref,
    unref,
    nextTick,
    getCurrentInstance
  } from 'vue';
  import sheep from '@/sheep';
  import accountLogin from './components/account-login.vue';
  import smsLogin from './components/sms-login.vue';
  import resetPassword from './components/reset-password.vue';
  import changeMobile from './components/change-mobile.vue';
  import changePassword from './components/change-password.vue';
  import mpAuthorization from './components/mp-authorization.vue';
  import {
    password,
    code
  } from '@/sheep/validate/form';
  import {
    closeAuthModal,
    showAuthModal
  } from '@/sheep/hooks/useModal';
  import AuthUtil from '@/sheep/api/member/auth';
  const isProcessing = ref(false);
  const modalStore = sheep.$store('modal');
  const accountLoginRef = ref(null);
  const verifiCode = ref(null);
  const captchaEnabled = ref(true)
  // 授权弹窗类型
  const authType = computed(() => modalStore.auth);
  const state = reactive({
    model: {
      username: '', // 账号
      password: '', // 密码
      captchaVerification: '' //验证码
    },
    rules: {
      password,
      code
    },
    protocol: false,
  });

  const currentProtocol = ref(false);

  // 勾选协议
  const onChange = () => {
    state.protocol = !state.protocol;
    isProcessing.value = state.protocol ? true : false;
  }

  // 查看协议
  const onProtocol = (title) => {
    closeAuthModal();
    sheep.$router.go('/pages/public/richtext', {
      title,
    });
  }

  // 点击登录 / 注册事件
  const onConfirm = (e) => {
    currentProtocol.value = e;
    setTimeout(() => {
      currentProtocol.value = false;
    }, 1000);
  }

  // 账号登录
  const accountLoginSubmit = async () => {
    if (!state.model.username) {
      sheep.$helper.toast('请输入用户名');
      return;
    }
    // 表单验证
    const validate = await unref(accountLoginRef)
      .validate()
      .catch((error) => {
        console.log('error: ', error);
      });
    if (!validate) return;

    if (verifiCode.value && !verifiCode.value.verification(state.model.captchaVerification)) {
      sheep.$helper.toast('请输入正确验证码');
      return
    }
    // 同意协议
    if (!state.protocol) {
      currentProtocol.value = true;
      setTimeout(() => {
        currentProtocol.value = false;
      }, 1000);
      sheep.$helper.toast('请勾选同意');
      return;
    }
    let sendData = {
      username: state.model.username, // 账号
      password: state.model.password, // 密码
      captchaVerification: '', //验证码
      isMgr: true
    }
    // 提交数据
    const {
      code,
      data
    } = await AuthUtil.login(sendData);
    if (code === 0) {
      const userInfo = await sheep.$store('user').getInfo();
      closeAuthModal();
    }
  }

  // 第三方授权登陆（微信小程序、Apple）
  const thirdLogin = async (provider) => {
    if (!state.protocol) {
      currentProtocol.value = true;
      setTimeout(() => {
        currentProtocol.value = false;
      }, 1000);
      sheep.$helper.toast('请勾选同意');
      return;
    }
    const loginRes = await sheep.$platform.useProvider(provider).login();
    if (loginRes) {
      const userInfo = await sheep.$store('user').getInfo();
      closeAuthModal();
      // 如果用户已经有头像和昵称，不需要再次授权
      if (userInfo.avatar && userInfo.nickname) {
        return;
      }

      // 触发小程序授权信息弹框
      // #ifdef MP-WEIXIN
      showAuthModal('mpAuthorization');
      // #endif
    }
  };

  // 微信小程序的“手机号快速验证”：https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html
  const get = async () => {
    if (!state.protocol) {
      currentProtocol.value = true;
      setTimeout(() => {
        currentProtocol.value = false;
      }, 1000);
      sheep.$helper.toast('请勾选同意');
      return;
    }

    isProcessing.value = true;
  };
  const getPhoneNumber = async (e) => {
    if (e.detail.errMsg !== 'getPhoneNumber:ok') {
      sheep.$helper.toast('快捷登录失败');
      return;
    }
    await sheep.$platform.useProvider().mobileLogin(e.detail);
    let Info =
      '获取您的昵称、头像' +
      '\r\n' +
      '获取微信头像和昵称，主要用于向用户提供具有辨识度的用户中心界面';
    uni.showModal({
      title: '微信授权',
      content: Info,
      confirmText: '允许',
      cancelText: '拒绝',
      success: async (res) => {
        if (res.confirm) {
          console.log('用户点击确定');
          let result = await sheep.$platform.useProvider('wechat').bind();
          if (result) {
            showAuthModal('mpAuthorization');
          }
        } else if (res.cancel) {
          console.log('用户点击取消');
          closeAuthModal();
        }
      },
    });
  };
</script>

<style lang="scss" scoped>
  @import './index.scss';

  .vf-code {
    ::v-deep .uni-forms-item__content {
      // width: 100%;
      display: flex !important;
      align-items: center;
      justify-content: space-between;
    }

    ::v-deep .uni-easyinput__content {
      width: 340rpx !important;
    }
  }

  ::v-deep .uni-error-message {
    bottom: 0 !important;
  }

  ::v-deep .uni-easyinput__content {
    // background: #f3f3f3 !important;
    border-radius: 42rpx !important;
  }



  .login-box {
    width: 100vw;
    min-height: 100vh;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;

    .avatar-img {
      width: 220rpx;
      height: 220rpx;
      border-radius: 50%;
    }

    .tit {
      font-size: 38rpx;
      font-weight: bold;
    }



    .login-btn-start {
      width: 100%;
      height: 72rpx;
      line-height: 72rpx;
      border-radius: 42rpx;
      background: linear-gradient(90deg, #ff3000, #ff300099);
    }

    .tcp-text {
      color: #ff3000 !important;
    }
  }

  .shake {
    animation: shake 0.05s linear 4 alternate;
  }

  @keyframes shake {
    from {
      transform: translateX(-10rpx);
    }

    to {
      transform: translateX(10rpx);
    }
  }

  .register-box {
    position: relative;
    justify-content: center;

    .register-btn {
      color: #999999;
      font-size: 30rpx;
      font-weight: 500;
    }

    .register-title {
      color: #999999;
      font-size: 30rpx;
      font-weight: 400;
      margin-right: 24rpx;
    }

    .or-title {
      margin: 0 16rpx;
      color: #999999;
      font-size: 30rpx;
      font-weight: 400;
    }

    .login-btn {
      color: var(--ui-BG-Main);
      font-size: 30rpx;
      font-weight: 500;
    }

    .circle {
      position: absolute;
      right: 0rpx;
      top: 18rpx;
      width: 8rpx;
      height: 8rpx;
      border-radius: 8rpx;
      background: var(--ui-BG-Main);
    }
  }

  .safe-box {
    height: calc(constant(safe-area-inset-bottom) / 5 * 3);
    height: calc(env(safe-area-inset-bottom) / 5 * 3);
  }



  .agreement-text {
    color: $dark-9;
  }

  // .login-btn-start {
  //   width: 200rpx;
  // }
</style>